package com.qf.rbac.sys.controller;

import com.qf.rbac.sys.entity.SysDept;
import com.qf.rbac.sys.service.ISysDeptService;
import com.qf.rbac.utils.Constants;
import com.qf.rbac.utils.R;
import net.bytebuddy.asm.Advice;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 部门管理 前端控制器
 * </p>
 *
 * @author dongjl
 * @since 2022-04-16
 */
@RestController
@RequestMapping("/sys/dept")
public class SysDeptController extends AbstractController{

    @Autowired
    ISysDeptService sysDeptService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:dept:list")
    public List<SysDept> list(){
//        List<SysDept> deptList = sysDeptService.listByMap(new HashMap<String, Object>());
        List<SysDept> deptList = sysDeptService.list(new HashMap<String, Object>());
        return deptList;
    }

    /**
     * 上级部门Id(管理员则为0)
     */
    @RequestMapping("/info")
    @RequiresPermissions("sys:dept:list")
    public R info(){
        long deptId = 0;
        if(getUser().getUserId() != Constants.SUPER_ADMIN){
            List<SysDept> deptList = sysDeptService.list();
            Long parentId = null;
            for(SysDept sysDeptEntity : deptList){
                if(parentId == null){
                    parentId = sysDeptEntity.getParentId();
                    continue;
                }

                if(parentId > sysDeptEntity.getParentId().longValue()){
                    parentId = sysDeptEntity.getParentId();
                }
            }
            deptId = parentId;
        }

        return R.ok().put("deptId", deptId);
    }
}
